home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / answers / compression-faq / part2 < prev    next >
Encoding:
Internet Message Format  |  1993-06-09  |  56.2 KB

  1. Path: senator-bedfellow.mit.edu!enterpoop.mit.edu!gatech!howland.reston.ans.net!usc!elroy.jpl.nasa.gov!swrinde!cs.utexas.edu!utnut!torn!nott!bnrgate!bnr.co.uk!pipex!uknet!mcsun!julienas!chorus!chorus.fr
  2. From: jloup@chorus.fr (Jean-loup Gailly)
  3. Newsgroups: comp.compression,news.answers,comp.answers
  4. Subject: comp.compression Frequently Asked Questions (part 2/3)
  5. Summary: *** READ THIS BEFORE POSTING ***
  6. Keywords: data compression, FAQ
  7. Message-ID: <compr2_9jun93@chorus.fr>
  8. Date: 9 Jun 93 13:23:36 GMT
  9. Expires: 30 Jul 93 16:17:20 GMT
  10. References: <compr1_9jun93@chorus.fr>
  11. Sender: news@chorus.chorus.fr
  12. Reply-To: jloup@chorus.fr
  13. Followup-To: comp.compression
  14. Lines: 1102
  15. Approved: news-answers-request@MIT.Edu
  16. Supersedes: <compr2_19may93@chorus.fr>
  17. Xref: senator-bedfellow.mit.edu comp.compression:7821 news.answers:9221 comp.answers:927
  18.  
  19. Archive-name: compression-faq/part2
  20. Last-modified: Feb 9th, 1993
  21.  
  22. This file is part 2 of a set of Frequently Asked Questions for the
  23. groups comp.compression and comp.compression.research.
  24. If you did not get part 1 or 3, you can get them by ftp
  25. on rtfm.mit.edu in directory
  26.    /pub/usenet/news.answers/compression-faq
  27.  
  28. If you don't want to see this FAQ regularly, please add the subject
  29. line to your kill file. If you have corrections or suggestions for
  30. this FAQ, send them to Jean-loup Gailly <jloup@chorus.fr>.  Thank you.
  31.  
  32. Contents
  33. ========
  34.  
  35. Part 2: (Long) introductions to data compression techniques
  36.  
  37. [70] Introduction to data compression (long)
  38.        Huffman and Related Compression Techniques
  39.        Arithmetic Coding
  40.        Substitutional Compressors
  41.           The LZ78 family of compressors
  42.           The LZ77 family of compressors
  43.  
  44. [71] Introduction to MPEG (long)
  45.        What is MPEG?
  46.        Does it have anything to do with JPEG?
  47.        Then what's JBIG and MHEG?
  48.        What has MPEG accomplished?
  49.        So how does MPEG I work?
  50.        What about the audio compression?
  51.        So how much does it compress?
  52.        What's phase II?
  53.        When will all this be finished?
  54.        How do I join MPEG?
  55.        How do I get the documents, like the MPEG I draft?
  56.  
  57. [72] What is wavelet theory?
  58. [73] What is the theoretical compression limit?
  59. [74] Introduction to JBIG
  60. [75] Introduction to JPEG
  61.  
  62. Part 3: (Long) list of image compression hardware
  63.  
  64. [85] Image compression hardware
  65. [99] Acknowledgments
  66.  
  67.  
  68. Search for "Subject: [#]" to get to question number # quickly. Some news
  69. readers can also take advantage of the message digest format used here.
  70.  
  71. ------------------------------------------------------------------------------
  72.  
  73. Subject: [70] Introduction to data compression (long)
  74.  
  75.  
  76. Written by Peter Gutmann <pgut1@cs.aukuni.ac.nz>.
  77.  
  78.  Huffman and Related Compression Techniques
  79.  ------------------------------------------
  80.  
  81.   *Huffman compression* is a statistical data compression technique which 
  82. gives a reduction in the average code length used to represent the symbols of 
  83. a alphabet.  The Huffman code is an example of a code which is optimal in the 
  84. case where all symbols probabilities are integral powers of 1/2.  A Huffman 
  85. code can be built in the following manner:
  86.  
  87.   (1) Rank all symbols in order of probability of occurrence.
  88.     
  89.   (2) Successively combine the two symbols of the lowest probability to form
  90.       a new composite symbol; eventually we will build a binary tree where
  91.       each node is the probability of all nodes beneath it.
  92.  
  93.   (3) Trace a path to each leaf, noticing the direction at each node.
  94.  
  95.   For a given frequency distribution, there are many possible Huffman codes,
  96. but the total compressed length will be the same. It is possible to
  97. define a 'canonical' Huffman tree, that is, pick one of these alternative
  98. trees. Such a canonical tree can then be represented very compactly, by
  99. transmitting only the bit length of each code. This technique is used
  100. in most archivers (pkzip, lha, zoo, arj, ...).
  101.  
  102.  
  103.   A technique related to Huffman coding is *Shannon-Fano coding*, which was 
  104. suggested by Shannon and Weaver in 1949 and modified by Fano in 1961.  It 
  105. works as follows:
  106.  
  107.   (1) Divide the set of symbols into two equal or almost equal subsets
  108.       based on the probability of occurrence of characters in each
  109.       subset.  The first subset is assigned a binary zero, the second
  110.       a binary one.
  111.  
  112.   (2) Repeat step (1) until all subsets have a single element.
  113.  
  114. The algorithm used to create the Huffman codes is bottom-up, and the
  115. one for the Shannon-Fano codes is top-down. Huffman encoding always
  116. generates optimal codes, Shannon-Fano sometimes uses a few more bits.
  117.  
  118.  
  119.  Arithmetic Coding
  120.  -----------------
  121.  
  122.   It would appear that Huffman or Shannon-Fano coding is the perfect
  123. means of compressing data.  However, this is *not* the case.  As
  124. mentioned above, these coding methods are optimal when and only when
  125. the symbol probabilities are integral powers of 1/2, which is usually
  126. not the case.
  127.  
  128.   The technique of *arithmetic coding* does not have this restriction:
  129. It achieves the same effect as treating the message as one single unit
  130. (a technique which would, for Huffman coding, require enumeration of
  131. every single possible message), and thus attains the theoretical
  132. entropy bound to compression efficiency for any source.
  133.  
  134.   Arithmetic coding works by representing a number by an interval of real 
  135. numbers between 0 and 1.  As the message becomes longer, the interval needed 
  136. to represent it becomes smaller and smaller, and the number of bits needed to 
  137. specify that interval increases.  Successive symbols in the message reduce 
  138. this interval in accordance with the probability of that symbol. The more
  139. likely symbols reduce the range by less, and thus add fewer bits to the   
  140. message.
  141.  
  142.      1                                             Codewords
  143.     +-----------+-----------+-----------+           /-----\
  144.     |           |8/9 YY     |  Detail   |<- 31/32    .11111
  145.     |           +-----------+-----------+<- 15/16    .1111
  146.     |    Y      |           | too small |<- 14/16    .1110
  147.     |2/3        |    YX     | for text  |<- 6/8      .110
  148.     +-----------+-----------+-----------+
  149.     |           |           |16/27 XYY  |<- 10/16    .1010
  150.     |           |           +-----------+
  151.     |           |    XY     |           |
  152.     |           |           |   XYX     |<- 4/8      .100
  153.     |           |4/9        |           |
  154.     |           +-----------+-----------+
  155.     |           |           |           |
  156.     |    X      |           |   XXY     |<- 3/8      .011
  157.     |           |           |8/27       |
  158.     |           |           +-----------+
  159.     |           |    XX     |           |
  160.     |           |           |           |<- 1/4      .01
  161.     |           |           |   XXX     |
  162.     |           |           |           |
  163.     |0          |           |           |
  164.     +-----------+-----------+-----------+
  165.  
  166.   As an example of arithmetic coding, lets consider the example of two
  167. symbols X and Y, of probabilities 0.66 and 0.33. To encode this message, we
  168. examine the first symbol: If it is a X, we choose the lower partition; if
  169. it is a Y, we choose the upper partition.  Continuing in this manner for
  170. three symbols, we get the codewords shown to the right of the diagram above
  171. - they can be found by simply taking an appropriate location in the
  172. interval for that particular set of symbols and turning it into a binary
  173. fraction. In practice, it is also necessary to add a special end-of-data
  174. symbol, which is not represented in this simpe example.
  175.         
  176.   In this case the arithmetic code is not completely efficient, which is due 
  177. to the shortness of the message - with longer messages the coding efficiency 
  178. does indeed approach 100%.
  179.  
  180.   Now that we have an efficient encoding technique, what can we do with it? 
  181. What we need is a technique for building a model of the data which we can 
  182. then use with the encoder.  The simplest model is a fixed one, for example a 
  183. table of standard letter frequencies for English text which we can then use 
  184. to get letter probabilities.  An improvement on this technique is to use an 
  185. *adaptive model*, in other words a model which adjusts itself to the data 
  186. which is being compressed as the data is compressed.  We can convert the 
  187. fixed model into an adaptive one by adjusting the symbol frequencies after 
  188. each new symbol is encoded, allowing the model to track the data being 
  189. transmitted.  However, we can do much better than that.
  190.  
  191. Using the symbol probabilities by themselves is not a particularly good
  192. estimate of the true entropy of the data: We can take into account
  193. intersymbol probabilities as well.  The best compressors available today
  194. take this approach: DMC (Dynamic Markov Coding) starts with a zero-order
  195. Markov model and gradually extends this initial model as compression
  196. progresses; PPM (Prediction by Partial Matching) looks for a match of the
  197. text to be compressed in an order-n context.  If no match is found, it
  198. drops to an order n-1 context, until it reaches order 0.  Both these
  199. techniques thus obtain a much better model of the data to be compressed,
  200. which, combined with the use of arithmetic coding, results in superior
  201. compression performance.
  202.  
  203.   So if arithmetic coding-based compressors are so powerful, why are they not 
  204. used universally?  Apart from the fact that they are relatively new and 
  205. haven't come into general use too much yet, there is also one major concern:  
  206. The fact that they consume rather large amounts of computing resources, both 
  207. in terms of CPU power and memory.  The building of sophisticated models for 
  208. the compression can chew through a fair amount of memory (especially in the 
  209. case of DMC, where the model can grow without bounds); and the arithmetic 
  210. coding itself involves a fair amount of number crunching.
  211. There is however an alternative approach, a class of compressors generally 
  212. referred to as *substitutional* or *dictionary-based compressors*.
  213.  
  214.  Substitutional Compressors
  215.  --------------------------
  216.  
  217.   The basic idea behind a substitutional compressor is to replace an 
  218. occurrence of a particular phrase or group of bytes in a piece of data with a 
  219. reference to a previous occurrence of that phrase.  There are two main 
  220. classes of schemes, named after Jakob Ziv and Abraham Lempel, who first 
  221. proposed them in 1977 and 1978.
  222.  
  223. <The LZ78 family of compressors>
  224.  
  225.   LZ78-based schemes work by entering phrases into a *dictionary* and then, 
  226. when a repeat occurrence of that particular phrase is found, outputting the 
  227. dictionary index instead of the phrase.  There exist several compression 
  228. algorithms based on this principle, differing mainly in the manner in which 
  229. they manage the dictionary.  The most well-known scheme (in fact the most 
  230. well-known of all the Lempel-Ziv compressors, the one which is generally (and 
  231. mistakenly) referred to as "Lempel-Ziv Compression"), is Terry Welch's LZW 
  232. scheme, which he designed in 1984 for implementation in hardware for high- 
  233. performance disk controllers.
  234.  
  235. Input string: /WED/WE/WEE/WEB
  236.  
  237. Character input:    Code output:    New code value and associated string:
  238.     /W                  /                   256 = /W
  239.     E                   W                   257 = WE
  240.     D                   E                   258 = ED
  241.     /                   D                   259 = D/
  242.     WE                  256                 260 = /WE
  243.     /                   E                   261 = E/
  244.     WEE                 260                 262 = /WEE
  245.     /W                  261                 263 = E/W
  246.     EB                  257                 264 = WEB
  247.     <END>               B
  248.     
  249.   LZW starts with a 4K dictionary, of which entries 0-255 refer to individual 
  250. bytes, and entries 256-4095 refer to substrings.  Each time a new code is 
  251. generated it means a new string has been parsed.  New strings are generated 
  252. by appending the current character K to the end of an existing string w.  The 
  253. algorithm for LZW compression is as follows:
  254.  
  255.   set w = NIL
  256.   loop
  257.       read a character K
  258.       if wK exists is in the dictionary
  259.           w = wK
  260.       else
  261.           output the code for w
  262.           add wK to the string table
  263.           w = K
  264.   endloop
  265.  
  266.   A sample run of LZW over a (highly redundant) input string can be seen in 
  267. the diagram above.  The strings are built up character-by-character starting 
  268. with a code value of 256.  LZW decompression takes the stream of codes and 
  269. uses it to exactly recreate the original input data.  Just like the 
  270. compression algorithm, the decompressor adds a new string to the dictionary 
  271. each time it reads in a new code.  All it needs to do in addition is to 
  272. translate each incoming code into a string and send it to the output.  A 
  273. sample run of the LZW decompressor is shown in below.
  274.  
  275. Input code: /WED<256>E<260><261><257>B
  276.  
  277. Input code:        Output string:     New code value and associated string:
  278.     /                  /            
  279.     W                  W                      256 = /W
  280.     E                  E                      257 = WE
  281.     D                  D                      258 = ED
  282.     256                /W                     259 = D/
  283.     E                  E                      260 = /WE
  284.     260                /WE                    261 = E/
  285.     261                E/                     262 = /WEE
  286.     257                WE                     263 = E/W
  287.     B                  B                      264 = WEB
  288.            
  289.   The most remarkable feature of this type of compression is that the entire 
  290. dictionary has been transmitted to the decoder without actually explicitly 
  291. transmitting the dictionary.  At the end of the run, the decoder will have a 
  292. dictionary identical to the one the encoder has, built up entirely as part of 
  293. the decoding process.
  294.     LZW is more commonly encountered today in a variant known as LZC, after 
  295. its use in the UNIX "compress" program.  In this variant, pointers do not 
  296. have a fixed length.  Rather, they start with a length of 9 bits, and then 
  297. slowly grow to their maximum possible length once all the pointers of a 
  298. particular size have been used up.  Furthermore, the dictionary is not frozen 
  299. once it is full as for LZW - the program continually monitors compression 
  300. performance, and once this starts decreasing the entire dictionary is 
  301. discarded and rebuilt from scratch.  More recent schemes use some sort of 
  302. least-recently-used algorithm to discard little-used phrases once the 
  303. dictionary becomes full rather than throwing away the entire dictionary.  
  304.  
  305. Finally, not all schemes build up the dictionary by adding a single new 
  306. character to the end of the current phrase. An alternative technique is to 
  307. concatenate the previous two phrases (LZMW), which results in a faster 
  308. buildup of longer phrases than the character-by-character buildup of the 
  309. other methods.  The disadvantage of this method is that a more sophisticated 
  310. data structure is needed to handle the dictionary.
  311.  
  312. [A good introduction to LZW, MW, AP and Y coding is given in the yabba
  313. package. For ftp information, see question 2 in part one, file type .Y]
  314.  
  315.  
  316. <The LZ77 family of compressors>
  317.  
  318.   LZ77-based schemes keep track of the last n bytes of data seen, and when a 
  319. phrase is encountered that has already been seen, they output a pair of 
  320. values corresponding to the position of the phrase in the previously-seen 
  321. buffer of data, and the length of the phrase.  In effect the compressor moves 
  322. a fixed-size *window* over the data (generally referred to as a *sliding 
  323. window*), with the position part of the (position, length) pair referring to 
  324. the position of the phrase within the window.  The most commonly used 
  325. algorithms are derived from the LZSS scheme described by James Storer and 
  326. Thomas Szymanski in 1982.  In this the compressor maintains a window of size 
  327. N bytes and a *lookahead buffer* the contents of which it tries to find a 
  328. match for in the window:
  329.  
  330.   while( lookAheadBuffer not empty )
  331.       {
  332.       get a pointer ( position, match ) to the longest match in the window
  333.           for the lookahead buffer;
  334.  
  335.       if( length > MINIMUM_MATCH_LENGTH )
  336.           {
  337.           output a ( position, length ) pair;
  338.           shift the window length characters along;
  339.           }
  340.       else
  341.           {
  342.           output the first character in the lookahead buffer;
  343.           shift the window 1 character along;
  344.           }
  345.       }
  346.         
  347.   Decompression is simple and fast:  Whenever a ( position, length ) pair is 
  348. encountered, go to that ( position ) in the window and copy ( length ) bytes 
  349. to the output.
  350.  
  351.   Sliding-window-based schemes can be simplified by numbering the input text
  352. characters mod N, in effect creating a circular buffer.  The sliding window
  353. approach automatically creates the LRU effect which must be done explicitly in
  354. LZ78 schemes.  Variants of this method apply additional compression to the
  355. output of the LZSS compressor, which include a simple variable-length code
  356. (LZB), dynamic Huffman coding (LZH), and Shannon-Fano coding (ZIP 1.x)), all
  357. of which result in a certain degree of improvement over the basic scheme,
  358. especially when the data are rather random and the LZSS compressor has little
  359. effect.
  360.   Recently an algorithm was developed which combines the ideas behind LZ77 and
  361. LZ78 to produce a hybrid called LZFG.  LZFG uses the standard sliding window,
  362. but stores the data in a modified trie data structure and produces as output
  363. the position of the text in the trie.  Since LZFG only inserts complete
  364. *phrases* into the dictionary, it should run faster than other LZ77-based
  365. compressors.
  366.  
  367. All popular archivers (arj, lha, zip, zoo) are variations on the LZ77 theme.
  368.  
  369. ------------------------------------------------------------------------------
  370.  
  371. Subject: [71] Introduction to MPEG (long)
  372.  
  373.  
  374. For MPEG players, see item 15 in part 1 of the FAQ.  Frank Gadegast
  375. <phade@cs.tu-berlin.de> also posts a FAQ specialized in MPEG.
  376.  
  377. Introduction written by Mark Adler <madler@cco.caltech.edu> around  
  378. January 1992 (and hence wildly out of date in this fast moving  
  379. area--any volunteers to update this section are welcome):
  380.  
  381. Q. What is MPEG?
  382. A. MPEG is a group of people that meet under ISO (the International
  383.    Standards Organization) to generate standards for digital video
  384.    (sequences of images in time) and audio compression.  In particular,
  385.    they define a compressed bit stream, which implicitly defines a
  386.    decompressor.  However, the compression algorithms are up to the
  387.    individual manufacturers, and that is where proprietary advantage
  388.    is obtained within the scope of a publicly available international
  389.    standard.  MPEG meets roughly four times a year for roughly a week
  390.    each time.  In between meetings, a great deal of work is done by
  391.    the members, so it doesn't all happen at the meetings.  The work
  392.    is organized and planned at the meetings.
  393.  
  394. Q. So what does MPEG stand for?
  395. A. Moving Pictures Experts Group.
  396.  
  397. Q. Does it have anything to do with JPEG?
  398. A. Well, it sounds the same, and they are part of the same subcommittee
  399.    of ISO along with JBIG and MHEG, and they usually meet at the same
  400.    place at the same time.  However, they are different sets of people
  401.    with few or no common individual members, and they have different
  402.    charters and requirements.  JPEG is for still image compression.
  403.  
  404. Q. Then what's JBIG and MHEG?
  405. A. Sorry I mentioned them. Ok, I'll simply say that JBIG is for binary
  406.    image compression (like faxes), and MHEG is for multi-media data
  407.    standards (like integrating stills, video, audio, text, etc.).
  408.    For an introduction to JBIG, see question 74 below.
  409.  
  410. Q. Ok, I'll stick to MPEG.  What has MPEG accomplished?
  411. A. So far (as of January 1992), they have completed the "Committee
  412.    Draft" of MPEG phase I, colloquially called MPEG I.  It defines
  413.    a bit stream for compressed video and audio optimized to fit into
  414.    a bandwidth (data rate) of 1.5 Mbits/s.  This rate is special
  415.    because it is the data rate of (uncompressed) audio CD's and DAT's.
  416.    The draft is in three parts, video, audio, and systems, where the
  417.    last part gives the integration of the audio and video streams
  418.    with the proper timestamping to allow synchronization of the two.
  419.    They have also gotten well into MPEG phase II, whose task is to
  420.    define a bitstream for video and audio coded at around 3 to 10
  421.    Mbits/s.
  422.  
  423. Q. So how does MPEG I work?
  424. A. First off, it starts with a relatively low resolution video
  425.    sequence (possibly decimated from the original) of about 352 by
  426.    240 frames by 30 frames/s (US--different numbers for Europe),
  427.    but original high (CD) quality audio.  The images are in color,
  428.    but converted to YUV space, and the two chrominance channels
  429.    (U and V) are decimated further to 176 by 120 pixels.  It turns
  430.    out that you can get away with a lot less resolution in those
  431.    channels and not notice it, at least in "natural" (not computer
  432.    generated) images.
  433.  
  434.    The basic scheme is to predict motion from frame to frame in the
  435.    temporal direction, and then to use DCT's (discrete cosine
  436.    transforms) to organize the redundancy in the spatial directions.
  437.    The DCT's are done on 8x8 blocks, and the motion prediction is
  438.    done in the luminance (Y) channel on 16x16 blocks.  In other words,
  439.    given the 16x16 block in the current frame that you are trying to
  440.    code, you look for a close match to that block in a previous or
  441.    future frame (there are backward prediction modes where later
  442.    frames are sent first to allow interpolating between frames).
  443.    The DCT coefficients (of either the actual data, or the difference
  444.    between this block and the close match) are "quantized", which
  445.    means that you divide them by some value to drop bits off the
  446.    bottom end.  Hopefully, many of the coefficients will then end up
  447.    being zero.  The quantization can change for every "macroblock"
  448.    (a macroblock is 16x16 of Y and the corresponding 8x8's in both
  449.    U and V).  The results of all of this, which include the DCT
  450.    coefficients, the motion vectors, and the quantization parameters
  451.    (and other stuff) is Huffman coded using fixed tables.  The DCT
  452.    coefficients have a special Huffman table that is "two-dimensional"
  453.    in that one code specifies a run-length of zeros and the non-zero
  454.    value that ended the run.  Also, the motion vectors and the DC
  455.    DCT components are DPCM (subtracted from the last one) coded.
  456.  
  457. Q. So is each frame predicted from the last frame?
  458. A. No.  The scheme is a little more complicated than that.  There are
  459.    three types of coded frames.  There are "I" or intra frames.  They
  460.    are simply a frame coded as a still image, not using any past
  461.    history.  You have to start somewhere.  Then there are "P" or
  462.    predicted frames.  They are predicted from the most recently
  463.    reconstructed I or P frame.  (I'm describing this from the point
  464.    of view of the decompressor.)  Each macroblock in a P frame can
  465.    either come with a vector and difference DCT coefficients for a
  466.    close match in the last I or P, or it can just be "intra" coded
  467.    (like in the I frames) if there was no good match.
  468.  
  469.    Lastly, there are "B" or bidirectional frames.  They are predicted
  470.    from the closest two I or P frames, one in the past and one in the
  471.    future.  You search for matching blocks in those frames, and try
  472.    three different things to see which works best.  (Now I have the
  473.    point of view of the compressor, just to confuse you.)  You try using
  474.    the forward vector, the backward vector, and you try averaging the
  475.    two blocks from the future and past frames, and subtracting that from
  476.    the block being coded.  If none of those work well, you can intra-
  477.    code the block.
  478.  
  479.    The sequence of decoded frames usually goes like:
  480.  
  481.    IBBPBBPBBPBBIBBPBBPB...
  482.  
  483.    Where there are 12 frames from I to I (for US and Japan anyway.)
  484.    This is based on a random access requirement that you need a
  485.    starting point at least once every 0.4 seconds or so.  The ratio
  486.    of P's to B's is based on experience.
  487.  
  488.    Of course, for the decoder to work, you have to send that first
  489.    P *before* the first two B's, so the compressed data stream ends
  490.    up looking like:
  491.  
  492.    0xx312645...
  493.  
  494.    where those are frame numbers.  xx might be nothing (if this is
  495.    the true starting point), or it might be the B's of frames -2 and
  496.    -1 if we're in the middle of the stream somewhere.
  497.  
  498.    You have to decode the I, then decode the P, keep both of those
  499.    in memory, and then decode the two B's.  You probably display the
  500.    I while you're decoding the P, and display the B's as you're
  501.    decoding them, and then display the P as you're decoding the next
  502.    P, and so on.
  503.  
  504. Q. You've got to be kidding.
  505. A. No, really!
  506.  
  507. Q. Hmm.  Where did they get 352x240?
  508. A. That derives from the CCIR-601 digital television standard which
  509.    is used by professional digital video equipment.  It is (in the US)
  510.    720 by 243 by 60 fields (not frames) per second, where the fields
  511.    are interlaced when displayed.  (It is important to note though
  512.    that fields are actually acquired and displayed a 60th of a second
  513.    apart.)  The chrominance channels are 360 by 243 by 60 fields a
  514.    second, again interlaced.  This degree of chrominance decimation
  515.    (2:1 in the horizontal direction) is called 4:2:2.  The source
  516.    input format for MPEG I, called SIF, is CCIR-601 decimated by 2:1
  517.    in the horizontal direction, 2:1 in the time direction, and an
  518.    additional 2:1 in the chrominance vertical direction.  And some
  519.    lines are cut off to make sure things divide by 8 or 16 where
  520.    needed.
  521.  
  522. Q. What if I'm in Europe?
  523. A. For 50 Hz display standards (PAL, SECAM) change the number of lines
  524.    in a field from 243 or 240 to 288, and change the display rate to
  525.    50 fields/s or 25 frames/s.  Similarly, change the 120 lines in
  526.    the decimated chrominance channels to 144 lines.  Since 288*50 is
  527.    exactly equal to 240*60, the two formats have the same source data
  528.    rate.
  529.  
  530. Q. You didn't mention anything about the audio compression.
  531. A. Oh, right.  Well, I don't know as much about the audio compression.
  532.    Basically they use very carefully developed psychoacoustic models
  533.    derived from experiments with the best obtainable listeners to
  534.    pick out pieces of the sound that you can't hear.  There are what
  535.    are called "masking" effects where, for example, a large component
  536.    at one frequency will prevent you from hearing lower energy parts
  537.    at nearby frequencies, where the relative energy vs. frequency
  538.    that is masked is described by some empirical curve.  There are
  539.    similar temporal masking effects, as well as some more complicated
  540.    interactions where a temporal effect can unmask a frequency, and
  541.    vice-versa.
  542.  
  543.    The sound is broken up into spectral chunks with a hybrid scheme
  544.    that combines sine transforms with subband transforms, and the
  545.    psychoacoustic model written in terms of those chunks.  Whatever
  546.    can be removed or reduced in precision is, and the remainder is
  547.    sent.  It's a little more complicated than that, since the bits
  548.    have to be allocated across the bands.  And, of course, what is
  549.    sent is entropy coded.
  550.  
  551. Q. So how much does it compress?
  552. A. As I mentioned before, audio CD data rates are about 1.5 Mbits/s.
  553.    You can compress the same stereo program down to 256 Kbits/s with
  554.    no loss in discernable quality.  (So they say.  For the most part
  555.    it's true, but every once in a while a weird thing might happen
  556.    that you'll notice.  However the effect is very small, and it takes
  557.    a listener trained to notice these particular types of effects.)
  558.    That's about 6:1 compression.  So, a CD MPEG I stream would have
  559.    about 1.25 MBits/s left for video.  The number I usually see though
  560.    is 1.15 MBits/s (maybe you need the rest for the system data
  561.    stream).  You can then calculate the video compression ratio from
  562.    the numbers here to be about 26:1.  If you step back and think
  563.    about that, it's little short of a miracle.  Of course, it's lossy
  564.    compression, but it can be pretty hard sometimes to see the loss,
  565.    if you're comparing the SIF original to the SIF decompressed.  There
  566.    is, however, a very noticeable loss if you're coming from CCIR-601
  567.    and have to decimate to SIF, but that's another matter.  I'm not
  568.    counting that in the 26:1.
  569.  
  570.    The standard also provides for other bit rates ranging from 32Kbits/s
  571.    for a single channel, up to 448 Kbits/s for stereo.
  572.  
  573. Q. What's phase II?
  574. A. As I said, there is a considerable loss of quality in going from
  575.    CCIR-601 to SIF resolution.  For entertainment video, it's simply
  576.    not acceptable.  You want to use more bits and code all or almost
  577.    all the CCIR-601 data.  From subjective testing at the Japan
  578.    meeting in November 1991, it seems that 4 MBits/s can give very
  579.    good quality compared to the original CCIR-601 material.  The
  580.    objective of phase II is to define a bit stream optimized for these
  581.    resolutions and bit rates.
  582.  
  583. Q. Why not just scale up what you're doing with MPEG I?
  584. A. The main difficulty is the interlacing.  The simplest way to extend
  585.    MPEG I to interlaced material is to put the fields together into
  586.    frames (720x486x30/s).  This results in bad motion artifacts that
  587.    stem from the fact that moving objects are in different places
  588.    in the two fields, and so don't line up in the frames.  Compressing
  589.    and decompressing without taking that into account somehow tends to
  590.    muddle the objects in the two different fields.
  591.  
  592.    The other thing you might try is to code the even and odd field
  593.    streams separately.  This avoids the motion artifacts, but as you
  594.    might imagine, doesn't get very good compression since you are not
  595.    using the redundancy between the even and odd fields where there
  596.    is not much motion (which is typically most of image).
  597.  
  598.    Or you can code it as a single stream of fields.  Or you can
  599.    interpolate lines.  Or, etc. etc.  There are many things you can
  600.    try, and the point of MPEG II is to figure out what works well.
  601.    MPEG II is not limited to consider only derivations of MPEG I.
  602.    There were several non-MPEG I-like schemes in the competition in
  603.    November, and some aspects of those algorithms may or may not
  604.    make it into the final standard for entertainment video compression.
  605.  
  606. Q. So what works?
  607. A. Basically, derivations of MPEG I worked quite well, with one that
  608.    used wavelet subband coding instead of DCT's that also worked very
  609.    well.  Also among the worked-very-well's was a scheme that did not
  610.    use B frames at all, just I and P's.  All of them, except maybe one,
  611.    did some sort of adaptive frame/field coding, where a decision is
  612.    made on a macroblock basis as to whether to code that one as one
  613.    frame macroblock or as two field macroblocks.  Some other aspects
  614.    are how to code I-frames--some suggest predicting the even field
  615.    from the odd field.  Or you can predict evens from evens and odds
  616.    or odds from evens and odds or any field from any other field, etc.
  617.  
  618. Q. So what works?
  619. A. Ok, we're not really sure what works best yet.  The next step is
  620.    to define a "test model" to start from, that incorporates most of
  621.    the salient features of the worked-very-well proposals in a
  622.    simple way.  Then experiments will be done on that test model,
  623.    making a mod at a time, and seeing what makes it better and what
  624.    makes it worse.  Example experiments are, B's or no B's, DCT vs.
  625.    wavelets, various field prediction modes, etc.  The requirements,
  626.    such as implementation cost, quality, random access, etc. will all
  627.    feed into this process as well.
  628.  
  629. Q. When will all this be finished?
  630. A. I don't know.  I'd have to hope in about a year or less.
  631.  
  632. Q. How do I join MPEG?
  633. A. You don't join MPEG.  You have to participate in ISO as part of a
  634.    national delegation.  How you get to be part of the national
  635.    delegation is up to each nation.  I only know the U.S., where you
  636.    have to attend the corresponding ANSI meetings to be able to
  637.    attend the ISO meetings.  Your company or institution has to be
  638.    willing to sink some bucks into travel since, naturally, these
  639.    meetings are held all over the world.  (For example, Paris,
  640.    Santa Clara, Kurihama Japan, Singapore, Haifa Israel, Rio de
  641.    Janeiro, London, etc.)
  642.  
  643. Q. Well, then how do I get the documents, like the MPEG I draft?
  644. A. MPEG is a draft ISO standard. It's exact name is ISO CD 11172.
  645.    The draft consists of three parts: System, Video, and Audio. The
  646.    System part (11172-1) deals with synchronization and multiplexing
  647.    of audio-visual information, while the Video (11172-2) and Audio
  648.    part (11172-3) address the video and the audio compression techniques
  649.    respectively.
  650.  
  651.    You may order it from your national standards body (e.g. ANSI in
  652.    the USA) or buy it from companies like
  653.      OMNICOM
  654.      phone +44 438 742424
  655.      FAX +44 438 740154
  656.  
  657. ------------------------------------------------------------------------------
  658.  
  659. Subject: [72] What is wavelet theory?
  660.  
  661.  
  662. Preprints and software are available by anonymous ftp from the
  663. Yale Mathematics Department computer ceres.math.yale.edu[130.132.23.22],
  664. in pub/wavelets and pub/software.
  665.  
  666. epic and hcompress are wavelet coders. (For source code, see item 15
  667. in part one).
  668.  
  669. Bill Press of Harvard/CfA has made some things available for anonymous
  670. ftp on cfata4.harvard.edu [128.103.40.79] in directory /pub. There is
  671. a short TeX article on wavelet theory (wavelet.tex, to be included in
  672. a future edition of Numerical Recipes), some sample wavelet code
  673. (wavelet.f, in FORTRAN - sigh), and a beta version of an astronomical
  674. image compression program which he is currently developing (FITS
  675. format data files only, in fitspress08.tar.Z).
  676.  
  677. A mailing list dedicated to research on wavelets has been set up at the
  678. University of South Carolina. To subscribe to this mailing list, send a
  679. message with "subscribe" as the subject to wavelet@math.scarolina.edu.
  680.  
  681.  
  682. A 5 minute course in wavelet transforms, by Richard Kirk <rak@crosfield.co.uk>:
  683.  
  684. Do you know what a Haar transform is? Its a transform to another orthonormal
  685. space (like the DFT), but the basis functions are a set of square wave bursts
  686. like this...
  687.  
  688.    +--+                         +------+
  689.    +  |  +------------------    +      |      +--------------
  690.       +--+                             +------+
  691.  
  692.          +--+                                 +------+
  693.    ------+  |  +------------    --------------+      |      +
  694.             +--+                                     +------+
  695.  
  696.                +--+             +-------------+
  697.    ------------+  |  +------    +             |             +
  698.                   +--+                        +-------------+
  699.  
  700.                      +--+       +---------------------------+
  701.    ------------------+  |  +    +                           +
  702.                         +--+
  703.  
  704. This is the set of functions for an 8-element 1-D Haar transform. You
  705. can probably see how to extend this to higher orders and higher dimensions
  706. yourself. This is dead easy to calculate, but it is not what is usually
  707. understood by a wavelet transform.
  708.  
  709. If you look at the eight Haar functions you see we have four functions
  710. that code the highest resolution detail, two functions that code the
  711. coarser detail, one function that codes the coarser detail still, and the 
  712. top function that codes the average value for the whole `image'.
  713.  
  714. Haar function can be used to code images instead of the DFT. With bilevel
  715. images (such as text) the result can look better, and it is quicker to code.
  716. Flattish regions, textures, and soft edges in scanned images get a nasty
  717. `blocking' feel to them. This is obvious on hardcopy, but can be disguised on
  718. color CRTs by the effects of the shadow mask. The DCT gives more consistent
  719. results.
  720.  
  721. This connects up with another bit of maths sometimes called Multispectral
  722. Image Analysis, sometimes called Image Pyramids.
  723.  
  724. Suppose you want to produce a discretely sampled image from a continuous 
  725. function. You would do this by effectively `scanning' the function using a
  726. sinc function [ sin(x)/x ] `aperture'. This was proved by Shannon in the 
  727. `forties. You can do the same thing starting with a high resolution
  728. discretely sampled image. You can then get a whole set of images showing 
  729. the edges at different resolutions by differencing the image at one
  730. resolution with another version at another resolution. If you have made this
  731. set of images properly they ought to all add together to give the original 
  732. image.
  733.  
  734. This is an expansion of data. Suppose you started off with a 1K*1K image.
  735. You now may have a 64*64 low resolution image plus difference images at 128*128
  736. 256*256, 512*512 and 1K*1K. 
  737.  
  738. Where has this extra data come from? If you look at the difference images you 
  739. will see there is obviously some redundancy as most of the values are near 
  740. zero. From the way we constructed the levels we know that locally the average
  741. must approach zero in all levels but the top. We could then construct a set of
  742. functions out of the sync functions at any level so that their total value 
  743. at all higher levels is zero. This gives us an orthonormal set of basis 
  744. functions for a transform. The transform resembles the Haar transform a bit,
  745. but has symmetric wave pulses that decay away continuously in either direction
  746. rather than square waves that cut off sharply. This transform is the
  747. wavelet transform ( got to the point at last!! ).
  748.  
  749. These wavelet functions have been likened to the edge detecting functions
  750. believed to be present in the human retina.
  751.  
  752.  
  753. Loren I. Petrich <lip@s1.gov> adds that order 2 or 3 Daubechies
  754. discrete wavelet transforms have a speed comparable to DCT's, and
  755. usually achieve compression a factor of 2 better for the same image
  756. quality than the JPEG 8*8 DCT. (See item 25 in part 1 of this FAQ for
  757. references on fast DCT algorithms.)
  758.  
  759. ------------------------------------------------------------------------------
  760.  
  761. Subject: [73] What is the theoretical compression limit?
  762.  
  763.  
  764. There is no compressor that is guaranteed to compress all possible input
  765. files. If it compresses some files, then it must enlarge some others.
  766. This can be proven by a simple counting argument (see question 9).
  767.  
  768. As an extreme example, the following algorithm achieves 100%
  769. compression for one special input file and enlarges all other files by
  770. only one bit:
  771.  
  772. - if the input data is <insert your favorite one here>, output an empty file.
  773. - otherwise output one bit (zero or one) followed by the input data.
  774.  
  775. The concept of theoretical compression limit is meaningful only
  776. if you have a model for your input data. See question 70 above
  777. for some examples of data models.
  778.  
  779. ------------------------------------------------------------------------------
  780.  
  781. Subject: [74] Introduction to JBIG
  782.  
  783.  
  784. A short introduction, written by Mark Adler <madler@cco.caltech.edu>:
  785.  
  786.   JBIG losslessly compresses binary (one-bit/pixel) images.  (The B stands
  787.   for bi-level.)  Basically it models the redundancy in the image as the
  788.   correlations of the pixel currently being coded with a set of nearby
  789.   pixels called the template.  An example template might be the two
  790.   pixels preceding this one on the same line, and the five pixels centered
  791.   above this pixel on the previous line.  Note that this choice only
  792.   involves pixels that have already been seen from a scanner.
  793.  
  794.   The current pixel is then arithmetically coded based on the eight-bit
  795.   (including the pixel being coded) state so formed.  So there are (in this
  796.   case) 256 contexts to be coded.  The arithmetic coder and probability
  797.   estimator for the contexts are actually IBM's (patented) Q-coder.  The
  798.   Q-coder uses low precision, rapidly adaptable (those two are related)
  799.   probability estimation combined with a multiply-less arithmetic coder.
  800.   The probability estimation is intimately tied to the interval calculations
  801.   necessary for the arithmetic coding.
  802.  
  803.   JBIG actually goes beyond this and has adaptive templates, and probably
  804.   some other bells and whistles I don't know about.  You can find a
  805.   description of the Q-coder as well as the ancestor of JBIG in the Nov 88
  806.   issue of the IBM Journal of Research and Development.  This is a very
  807.   complete and well written set of five articles that describe the Q-coder
  808.   and a bi-level image coder that uses the Q-coder.
  809.  
  810.   You can use JBIG on grey-scale or even color images by simply applying
  811.   the algorithm one bit-plane at a time.  You would want to recode the
  812.   grey or color levels first though, so that adjacent levels differ in
  813.   only one bit (called Gray-coding).  I hear that this works well up to
  814.   about six bits per pixel, beyond which JPEG's lossless mode works better.
  815.   You need to use the Q-coder with JPEG also to get this performance.
  816.  
  817.   Actually no lossless mode works well beyond six bits per pixel, since
  818.   those low bits tend to be noise, which doesn't compress at all.
  819.  
  820.   Anyway, the intent of JBIG is to replace the current, less effective
  821.   group 3 and 4 fax algorithms.
  822.  
  823.  
  824. Another introduction to JBIG, written by Hank van Bekkem <jbek@oce.nl>:
  825.  
  826.   The following description of the JBIG algorithm is derived from
  827.   experiences with a software implementation I wrote following the
  828.   specifications in the revision 4.1 draft of September 16, 1991. The
  829.   source will not be made available in the public domain, as parts of
  830.   JBIG are patented.
  831.  
  832.   JBIG (Joint Bi-level Image Experts Group) is an experts group of ISO,
  833.   IEC and CCITT (JTC1/SC2/WG9 and SGVIII). Its job is to define a
  834.   compression standard for lossless image coding ([1]). The main
  835.   characteristics of the proposed algorithm are:
  836.   - Compatible progressive/sequential coding. This means that a
  837.     progressively coded image can be decoded sequentially, and the
  838.     other way around.
  839.   - JBIG will be a lossless image compression standard: all bits in
  840.     your images before and after compression and decompression will be
  841.     exactly the same.
  842.  
  843.   In the rest of this text I will first describe the JBIG algorithm in
  844.   a short abstract of the draft. I will conclude by saying something
  845.   about the value of JBIG.
  846.  
  847.  
  848.   JBIG algorithm.
  849.   --------------
  850.  
  851.   JBIG parameter P specifies the number of bits per pixel in the image.
  852.   Its allowable range is 1 through 255, but starting at P=8 or so,
  853.   compression will be more efficient using other algorithms. On the
  854.   other hand, medical images such as chest X-rays are often stored with
  855.   12 bits per pixel, while no distorsion is allowed, so JBIG can
  856.   certainly be of use in this area. To limit the number of bit changes
  857.   between adjacent decimal values (e.g. 127 and 128), it is wise to use
  858.   Gray coding before compressing multi-level images with JBIG. JBIG
  859.   then compresses the image on a bitplane basis, so the rest of this
  860.   text assumes bi-level pixels.
  861.  
  862.   Progressive coding is a way to send an image gradually to a receiver
  863.   instead of all at once. During sending, more detail is sent, and the
  864.   receiver can build the image from low to high detail. JBIG uses
  865.   discrete steps of detail by successively doubling the resolution. The
  866.   sender computes a number of resolution layers D, and transmits these
  867.   starting at the lowest resolution Dl. Resolution reduction uses
  868.   pixels in the high resolution layer and some already computed low
  869.   resolution pixels as an index into a lookup table. The contents of
  870.   this table can be specified by the user.
  871.  
  872.   Compatibility between progressive and sequential coding is achieved
  873.   by dividing an image into stripes. Each stripe is a horizontal bar
  874.   with a user definable height. Each stripe is separately coded and
  875.   transmitted, and the user can define in which order stripes,
  876.   resolutions and bitplanes (if P>1) are intermixed in the coded data.
  877.   A progressive coded image can be decoded sequentially by decoding
  878.   each stripe, beginning by the one at the top of the image, to its
  879.   full resolution, and then proceeding to the next stripe. Progressive
  880.   decoding can be done by decoding only a specific resolution layer
  881.   from all stripes.
  882.  
  883.   After dividing an image into bitplanes, resolution layers and
  884.   stripes, eventually a number of small bi-level bitmaps are left to
  885.   compress. Compression is done using a Q-coder. Reference [2]
  886.   contains a full description, I will only outline the basic principles
  887.   here.
  888.  
  889.   The Q-coder codes bi-level pixels as symbols using the probability of
  890.   occurrence of these symbols in a certain context. JBIG defines two
  891.   kinds of context, one for the lowest resolution layer (the base
  892.   layer), and one for all other layers (differential layers).
  893.   Differential layer contexts contain pixels in the layer to be coded,
  894.   and in the corresponding lower resolution layer.
  895.  
  896.   For each combination of pixel values in a context, the probability
  897.   distribution of black and white pixels can be different. In an all
  898.   white context, the probability of coding a white pixel will be much
  899.   greater than that of coding a black pixel. The Q-coder assigns, just
  900.   like a Huffman coder, more bits to less probable symbols, and so
  901.   achieves compression. The Q-coder can, unlike a Huffmann coder,
  902.   assign one output codebit to more than one input symbol, and thus is
  903.   able to compress bi-level pixels without explicit clustering, as
  904.   would be necessary using a Huffman coder.
  905.  
  906.   Maximum compression will be achieved when all probabilities (one set
  907.   for each combination of pixel values in the context) follow the
  908.   probabilities of the pixels. The Q-coder therefore continuously
  909.   adapts these probabilities to the symbols it sees.
  910.  
  911.  
  912.   JBIG value.
  913.   ----------
  914.  
  915.   In my opinion, JBIG can be regarded as two combined devices:
  916.   - Providing the user the service of sending or storing multiple
  917.     representations of images at different resolutions without any
  918.     extra cost in storage. Differential layer contexts contain pixels
  919.     in two resolution layers, and so enable the Q-coder to effectively
  920.     code the difference in information between the two layers, instead
  921.     of the information contained in every layer. This means that,
  922.     within a margin of approximately 5%, the number of resolution
  923.     layers doesn't effect the compression ratio.
  924.   - Providing the user a very efficient compression algorithm, mainly
  925.     for use with bi-level images. Compared to CCITT Group 4, JBIG is
  926.     approximately 10% to 50% better on text and line art, and even
  927.     better on halftones. JBIG is however, just like Group 4, somewhat
  928.     sensitive to noise in images. This means that the compression ratio
  929.     decreases when the amount of noise in your images increases.
  930.  
  931.   An example of an application would be browsing through an image
  932.   database, e.g. an EDMS (engineering document management system).
  933.   Large A0 size drawings at 300 dpi or so would be stored using five
  934.   resolution layers. The lowest resolution layer would fit on a
  935.   computer screen. Base layer compressed data would be stored at the
  936.   beginning of the compressed file, thus making browsing through large
  937.   numbers of compressed drawings possible by reading and decompressing
  938.   just the first small part of all files. When the user stops browsing,
  939.   the system could automatically start decompressing all remaining
  940.   detail for printing at high resolution.
  941.  
  942.   [1] "Progressive Bi-level Image Compression, Revision 4.1", ISO/IEC
  943.       JTC1/SC2/WG9, CD 11544, September 16, 1991
  944.   [2] "An overview of the basic principles of the Q-coder adaptive
  945.       binary arithmetic coder", W.B. Pennebaker, J.L. Mitchell, G.G.
  946.       Langdon, R.B. Arps, IBM Journal of research and development,
  947.       Vol.32, No.6, November 1988, pp. 771-726 (See also the other
  948.       articles about the Q-coder in this issue)
  949.  
  950. ------------------------------------------------------------------------------
  951.  
  952. Subject: [75] Introduction to JPEG
  953.  
  954. Here is a brief overview of the inner workings of JPEG, plus some
  955. references for more detailed information, written by Tom Lane
  956. <tgl+@cs.cmu.edu>.  Please read item 19 in part 1 first.
  957.  
  958. JPEG works on either full-color or gray-scale images; it does not handle
  959. bilevel (black and white) images, at least not efficiently.  It doesn't
  960. handle colormapped images either; you have to pre-expand those into an
  961. unmapped full-color representation.  JPEG works best on "continuous tone"
  962. images; images with many sudden jumps in color values will not compress well.
  963.  
  964. There are a lot of parameters to the JPEG compression process.  By adjusting
  965. the parameters, you can trade off compressed image size against reconstructed
  966. image quality over a *very* wide range.  You can get image quality ranging
  967. from op-art (at 100x smaller than the original 24-bit image) to quite
  968. indistinguishable from the source (at about 3x smaller).  Usually the
  969. threshold of visible difference from the source image is somewhere around 10x
  970. to 20x smaller than the original, ie, 1 to 2 bits per pixel for color images.
  971. Grayscale requires a little bit less space.
  972.  
  973. JPEG defines a "baseline" lossy algorithm, plus optional extensions for
  974. progressive and hierarchical coding.  There is also a separate lossless
  975. compression mode; this typically gives about 2:1 compression, ie about 12
  976. bits per color pixel.  Most currently available JPEG hardware and software
  977. handles only the baseline mode.
  978.  
  979.  
  980. Here's the outline of the baseline compression algorithm:
  981.  
  982. 1. Transform the image into a suitable color space.  This is a no-op for
  983. grayscale, but for color images you generally want to transform RGB into a
  984. luminance/chrominance color space (YCbCr, YUV, etc).  The luminance component
  985. is grayscale and the other two axes are color information.  The reason for
  986. doing this is that you can afford to lose a lot more information in the
  987. chrominance components than you can in the luminance component; the human eye
  988. is not as sensitive to high-frequency color info as it is to high-frequency
  989. luminance.  (See any TV system for precedents.)  You don't have to change the
  990. color space if you don't want to, as the remainder of the algorithm works on
  991. each color component independently, and doesn't care just what the data is.
  992. However, compression will be less since you will have to code all the
  993. components at luminance quality.
  994.  
  995. 2. (Optional) Downsample each component by averaging together groups of
  996. pixels.  The luminance component is left at full resolution, while the color
  997. components are usually reduced 2:1 horizontally and either 2:1 or 1:1 (no
  998. change) vertically.  In JPEG-speak these alternatives are usually called
  999. 2h2v and 2h1v sampling, but you may also see the terms "411" and "422"
  1000. sampling.  This step immediately reduces the data volume by one-half or
  1001. one-third, while having almost no impact on perceived quality.  (Obviously
  1002. this would not be true if you tried it in RGB color space...)  Note that
  1003. downsampling is not applicable to gray-scale data.
  1004.  
  1005. 3. Group the pixel values for each component into 8x8 blocks.  Transform each
  1006. 8x8 block through a discrete cosine transform (DCT); this is a relative of the
  1007. Fourier transform and likewise gives a frequency map, with 8x8 components.
  1008. Thus you now have numbers representing the average value in each block and
  1009. successively higher-frequency changes within the block.  The motivation for
  1010. doing this is that you can now throw away high-frequency information without
  1011. affecting low-frequency information.  (The DCT transform itself is reversible
  1012. except for roundoff error.)  See question 25 for fast DCT algorithms.
  1013.  
  1014. 4. In each block, divide each of the 64 frequency components by a separate
  1015. "quantization coefficient", and round the results to integers.  This is the
  1016. fundamental information-losing step.  A Q.C. of 1 loses no information;
  1017. larger Q.C.s lose successively more info.  The higher frequencies are normally
  1018. reduced much more than the lower.  (All 64 Q.C.s are parameters to the
  1019. compression process; tuning them for best results is a black art.  It seems
  1020. likely that the best values are yet to be discovered.  Most existing coders
  1021. use simple multiples of the example tables given in the JPEG standard.)
  1022.  
  1023. 5. Encode the reduced coefficients using either Huffman or arithmetic coding.
  1024. (Strictly speaking, baseline JPEG only allows Huffman coding; arithmetic
  1025. coding is an optional extension.)   Notice that this step is lossless, so it
  1026. doesn't affect image quality.  The arithmetic coding option uses Q-coding;
  1027. it is identical to the coder used in JBIG (see question 74).  Be aware that
  1028. Q-coding is patented.  Most existing implementations support only the Huffman
  1029. mode, so as to avoid license fees.  The arithmetic mode offers maybe 5 or 10%
  1030. better compression, which isn't enough to justify paying fees.
  1031.  
  1032. 6. Tack on appropriate headers, etc, and output the result.  In an
  1033. "interchange" JPEG file, all of the compression parameters are included
  1034. in the headers so that the decompressor can reverse the process.  For
  1035. specialized applications, the spec permits the parameters to be omitted
  1036. from the file; this saves several hundred bytes of overhead, but it means
  1037. that the decompressor must know what parameters the compressor used.
  1038.  
  1039.  
  1040. The decompression algorithm reverses this process, and typically adds some
  1041. smoothing steps to reduce pixel-to-pixel discontinuities.
  1042.  
  1043.  
  1044. Extensions:
  1045.  
  1046. The progressive mode is intended to support real-time transmission of images.
  1047. It allows the DCT coefficients to be sent incrementally in multiple "scans"
  1048. of the image.  With each scan, the decoder can produce a higher-quality
  1049. rendition of the image.  Thus a low-quality preview can be sent very quickly,
  1050. then refined as time allows.  Notice that the decoder must do essentially a
  1051. full JPEG decode cycle for each scan, so this scheme is useful only with fast
  1052. decoders (meaning dedicated hardware, at least at present).  However, the
  1053. total number of bits sent can actually be somewhat less than is necessary in
  1054. the baseline mode, especially if arithmetic coding is used.  So progressive
  1055. coding might be useful even if the decoder will simply save up the bits and
  1056. make only one output pass.
  1057.  
  1058. The hierarchical mode represents an image at multiple resolutions.  For
  1059. example, one could provide 512x512, 1024x1024, and 2048x2048 versions of the
  1060. image.  The higher-resolution images are coded as differences from the next
  1061. smaller image, and thus require many fewer bits than they would if stored
  1062. independently.  (However, the total number of bits will be greater than that
  1063. needed to store just the highest-resolution frame.)  Note that the individual
  1064. frames in a hierarchical sequence may be coded progressively if desired.
  1065.  
  1066.  
  1067. Lossless JPEG:
  1068.  
  1069. The separate lossless mode does not use DCT, since roundoff errors prevent a
  1070. DCT calculation from being lossless.  For the same reason, one would not
  1071. normally use colorspace conversion or downsampling, although these are
  1072. permitted by the standard.  The lossless mode simply codes the difference
  1073. between each pixel and the "predicted" value for the pixel.  The predicted
  1074. value is a simple function of the already-transmitted pixels just above and
  1075. to the left of the current one (eg, their average; 8 different predictor
  1076. functions are permitted).  The sequence of differences is encoded using the
  1077. same back end (Huffman or arithmetic) used in the lossy mode.
  1078.  
  1079. The main reason for providing a lossless option is that it makes a good
  1080. adjunct to the hierarchical mode: the final scan in a hierarchical sequence
  1081. can be a lossless coding of the remaining differences, to achieve overall
  1082. losslessness.  This isn't quite as useful as it may at first appear, because
  1083. exact losslessness is not guaranteed unless the encoder and decoder have
  1084. identical IDCT implementations (ie identical roundoff errors).
  1085.  
  1086.  
  1087. References:
  1088.  
  1089. For a good technical introduction to JPEG, see:
  1090.     Wallace, Gregory K.  "The JPEG Still Picture Compression Standard",
  1091.     Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
  1092. (Adjacent articles in that issue discuss MPEG motion picture compression,
  1093. applications of JPEG, and related topics.)  If you don't have the CACM issue
  1094. handy, a PostScript file containing a revised version of this article is
  1095. available at ftp.uu.net, graphics/jpeg/wallace.ps.Z.  The file (actually a
  1096. preprint for an article to appear in IEEE Trans. Consum. Elect.) omits the
  1097. sample images that appeared in CACM, but it includes corrections and some
  1098. added material.  Note: the Wallace article is copyright ACM and IEEE, and
  1099. it may not be used for commercial purposes.
  1100.  
  1101. An alternative, more leisurely explanation of JPEG can be found in "The Data
  1102. Compression Book" by Mark Nelson ([Nel 1991], see question 7).  This book
  1103. provides excellent introductions to many data compression methods including
  1104. JPEG, plus sample source code in C.  The JPEG-related source code is far from
  1105. industrial-strength, but it's a pretty good learning tool.
  1106.  
  1107. An excellent textbook about JPEG is "JPEG Still Image Data Compression
  1108. Standard" by William B. Pennebaker and Joan L. Mitchell.  Published by Van
  1109. Nostrand Reinhold, 1993, ISBN 0-442-01272-1.  650 pages, price US$59.95.
  1110. (VNR will accept credit card orders at 800/842-3636, or get your local
  1111. bookstore to order it.)  This book includes the complete text of the ISO
  1112. JPEG standards, DIS 10918-1 and draft DIS 10918-2.  Review by Tom Lane:
  1113. "This is by far the most complete exposition of JPEG in existence.  It's
  1114. written by two people who know what they are talking about: both serve on the
  1115. ISO JPEG standards committee.  If you want to know how JPEG works or why it
  1116. works that way, this is the book to have."
  1117.  
  1118. The official specification of JPEG is not currently available on-line.
  1119. I hear that CCITT specs may be on-line sometime soon, which would change this.
  1120. At the moment, your best bet is to buy the Pennebaker and Mitchell textbook.
  1121.